package com.scalar.chiptrack.utils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * User: sujankumar.suppala
 * Date: Dec 27, 2005
 * Time: 4:57:08 PM
 */
public class WorkWeek
{
    int currentWWNumber;
    Date currentWWStartDate;
    int workWeekYear;

    private WorkWeek()
    {

    }
    public int getCurrentWWNumber()
    {
        return currentWWNumber;
    }

    public void setCurrentWWNumber(int currentWWNumber)
    {
        this.currentWWNumber = currentWWNumber;
    }

    public Date getCurrentWWStartDate()
    {
        return currentWWStartDate;
    }

    public void setCurrentWWStartDate(Date currentWWStartDate)
    {
        this.currentWWStartDate = currentWWStartDate;
    }

    public int getWorkWeekYear()
    {
        return workWeekYear;
    }

    public void setWorkWeekYear(int workWeekYear)
    {
        this.workWeekYear = workWeekYear;
    }
    public static WorkWeek getCurrentWorkWeekInstance ()
    {
        return getWorkWeekInstance( new Date() );
    }
    public static WorkWeek getWorkWeekInstance ( Date dateToFindWW )
    {
		Calendar ww = new GregorianCalendar();
        ww.setTime ( dateToFindWW );
        ww.setFirstDayOfWeek(Calendar.MONDAY);
		ww.setMinimalDaysInFirstWeek(4);
		int currentWWNumber = ww.get(Calendar.WEEK_OF_YEAR);
		//day of week number, Monday as starting day of week i.e 1(mon), 2(tue), 3(wed)..7(sun)
		int dayOfWeek = ww.get(Calendar.DAY_OF_WEEK) - (Calendar.MONDAY-1);
		if( dayOfWeek == 0 )
		{
			dayOfWeek = 7;
		}
		else if ( dayOfWeek < 0 )
		{
			dayOfWeek = 7 + dayOfWeek;
		}

		Calendar currentWWStartDate = Calendar.getInstance();
		currentWWStartDate.setTime( ww.getTime() );
		currentWWStartDate.add ( Calendar.DATE, -(dayOfWeek-1) );//move backward to monday
		int wwYear = currentWWStartDate.get ( Calendar.YEAR );
		if ( currentWWNumber == 1 )
		{
			if ( currentWWStartDate.get ( Calendar.DAY_OF_MONTH ) >= 29 )
			{
				wwYear = wwYear + 1;
			}
		}
        WorkWeek workWeek = new WorkWeek();
        workWeek.setCurrentWWNumber( currentWWNumber );
        workWeek.setWorkWeekYear( wwYear );
        workWeek.setCurrentWWStartDate( currentWWStartDate.getTime() );
        return workWeek;
    }
}
